import {useState} from "react";

/**
 * @param sort 排序字段
 * @param sortFn 排序接口
 * @param tableRef 表格ref
 */
const useTableSort = (sort, sortFn, tableRef) => {

  const [sortNum, setSortNum] = useState(null); //  排序值
  const [sortingKey, setSortingKey] = useState(null); //  排序

  //  确认排序
  const onSort = async (value, id) => {
    const params = {
      id,
      [sort]: Math.floor(value),
    };
    const res = await sortFn(params);
    if (res) {
      setSortingKey(null);
      tableRef.current.reload();
    }
  };

  //  排序键盘事件
  const sortKeyDown = (e, id) => {
    const {code, target: {value}} = e;
    if (code === 'Escape') {
      setSortingKey(null);
    } else if (code === 'Enter') {
      onSort(value, id);
    }
  };

  //  排序状态切换
  const onSorting = (row, value) => {
    setSortNum(value);
    setSortingKey(row.id);
  };

  return {
    sortNum,
    sortingKey,

    onSort,
    sortKeyDown,
    onSorting,
  }
}

export default useTableSort